package gui.storageunit;

import gui.common.*;
import gui.inventory.*;
import hit.core.HomeInventoryTracker;
import hit.core.StorageUnit;
import hit.core.TreeFacade;
import hit.dao.DataAccessObject;
import hit.dao.FactoryReference;

/**
 * Controller class for the edit storage unit view.
 */
public class EditStorageUnitController extends Controller 
										implements IEditStorageUnitController {
	
	TreeFacade facade;
	ProductContainerData toEdit;
	
	/**
	 * Constructor.
	 * 
	 * @param view Reference to edit storage unit view
	 * @param target The storage unit being edited
	 */
	public EditStorageUnitController(IView view, ProductContainerData target) {
		super(view);

		facade = HomeInventoryTracker.Instance().GetTreeFacade();
		toEdit = target;
		
		construct();
	}

	//
	// Controller overrides
	//
	
	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IEditStorageUnitView getView() {
		return (IEditStorageUnitView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() {
		
		String newName = this.getView().getStorageUnitName();
		
		boolean result = facade.CanEditStorageUnit((StorageUnit)toEdit.getTag(), newName);
		getView().enableOK(result);
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() {
		getView().setStorageUnitName(toEdit.getName());
	}

	//
	// IEditStorageUnitController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * edit storage unit view is changed by the user.
	 */
	@Override
	public void valuesChanged() {
		enableComponents();
	}

	/**
	 * This method is called when the user clicks the "OK"
	 * button in the edit storage unit view.
	 */
	@Override
	public void editStorageUnit() {
		try {
			String name = getView().getStorageUnitName();
			StorageUnit unit = (StorageUnit)toEdit.getTag();
			facade.EditStorageUnit(name, unit);
			
			DataAccessObject dao = FactoryReference.GetFactory().CreateDataAccessObject();
			
			dao.StartTransaction();
			
			dao.GetStorageUnitDAO().Update(unit);
			
			dao.EndTransaction(true);
			
			dao.CloseConnection();
		}
		catch (Exception e) {
			getView().displayErrorMessage(e.getMessage());
		}
	}

}

